<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>批量退库</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
<style type="text/css">
	.layui-table-click{
	    background-color:#ddf2e9 !important;
	}
</style>
</head>
<body>
	
<div class="x-nav">
	<span class="layui-breadcrumb">
		<a href="">首页</a>
		<a>
		  <cite>批量退库</cite>
		</a>
	</span>
</div>

<!-- 点击行的时候，把行ID存入 -->
<input class="layui-hide" id="cancellingStockId">
<input class="layui-hide" id="cancellingStockNumber">
<input class="layui-hide" id="cancellingType">
<input class="layui-hide" id="warehouseStockId">
<input class="layui-hide" id="customerId">

<div id="cancellingStockDiv" hidden>
	<form class="layui-form" id="cancellingStockForm">
		<xblock>
			<div class="layui-form-item">
				<input type="hidden" id="id" name="id">
				<input type="hidden" id="userId" name="userId">
				<input type="hidden" id="status" name="status">
				<input type="hidden" id="type" name="type" value="1">
			</div>
		<table>
			<tr>
				<td><label class="layui-form-label">退库单号</label></td>
				<td>
					<input readonly lay-verify="cancellingNumber" class="layui-input" type="text" id="cancellingNumber" name="cancellingNumber" style="width: 190px; display:inline">
					<div class="layui-inline" style="margin-top: 10px;">
						<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
					</div>
				</td>
				<td><label class="layui-form-label">创建日期</label></td>
				<td>
					<input lay-verify="createDate" class="layui-input" type="text" id="createDate" name="createDate" style="width: 190px; display:inline">
					<div class="layui-inline" style="margin-top: 12px;">
						<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
					</div>
				</td>
			</tr>
			<tr style="height: 10px"></tr>
			<tr>
				<td><label class="layui-form-label">退库原因</label></td>
				<td>
					<div style="width: 190px; float: left;">
						<select class="layui-input" name="reasonId" id="reasonId" lay-verify="reasonId"  lay-filter="reasonId">
							<option value="">请选择退库原因</option>
							<c:forEach items="${reasonList}" var="reason">
								<option value="${reason.id}">${reason.cancellingReason}</option>
							</c:forEach>
						</select>
					</div>
					<div style="margin-top: 12px;">
						<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
					</div>
				</td>

				<!-- <td><label class="layui-form-label">仓库类型</label></td>
				<td>
					<div style="width: 190px; float: left;">
						<select id="source" name="source" class="layui-select" lay-search="" lay-filter="source">
							<option value="">请选择仓库类型</option>
							<option value="1">良品库</option>
							<option value="0">不良品库</option>
						</select>
					</div>
					<div style="margin-top: 12px;">
						<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
					</div>
				</td> -->
				<td><label class="layui-form-label">供应商单号</label></td>
				<td>
					<input class="layui-input" type="text" id="customer_order" name="customer_order" style="width: 190px">
				</td>
			</tr>
			<tr style="height: 10px"></tr>
			<tr>
				<td><label class="layui-form-label">仓库名称</label></td>
				<td>
					<div style="width: 190px; float: left;">
						<select class="layui-input" name="warehouseId" id="warehouseId" lay-verify="warehouseId"  lay-filter="warehouseId">
							<option value="">请选择仓库名称</option>
							<c:forEach items="${warehouseList}" var="warehouse">
								<option value="${warehouse.id}">${warehouse.warehouse_name}</option>
							</c:forEach>
						</select>
					</div>
					<div style="margin-top: 12px;">
						<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
					</div>
				</td>
				<td><label class="layui-form-label">管理员姓名</label></td>
				<td>
					<input lay-verify="userName" readonly class="layui-input" id="userName" name="userName" style="color: gray; width: 190px">
				</td>
			</tr>
			<tr style="height: 10px"></tr>
			<tr>
				<td><label class="layui-form-label">管理员电话</label></td>
				<td>
					<input class="layui-input" readonly id="phone" name="phone" style="color: gray; width: 190px">
				</td>
				<td><label class="layui-form-label">仓库地址</label></td>
				<td>
					<input lay-verify="warehouse_address" readonly class="layui-input" id="warehouse_address" name="warehouse_address" style="color: gray; width: 190px">
				</td>
			</tr>
			<tr style="height: 10px"></tr>
			<tr>
				<td><label class="layui-form-label">供应商名称</label></td>
				<td>
					<div style="width: 190px; float: left;">
						<select class="layui-input" name="clientId" id="clientId" lay-verify="clientId"  lay-filter="clientId">
							<option value="">请选择供应商</option>
							<c:forEach items="${customerList}" var="customer">
								<option value="${customer.id}">${customer.customer_name}</option>
							</c:forEach>
						</select>
					</div>
					<div style="margin-top: 12px;">
						<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
					</div>
				</td>
				<td><label class="layui-form-label">供应商负责人</label></td>
				<td>
					<input lay-verify="contacts_name" readonly class="layui-input" id="contacts_name" name="contacts_name" style="color: gray; width: 190px">
				</td>
			</tr>
			<tr style="height: 10px"></tr>
			<tr>
				<td><label class="layui-form-label">供应商电话</label></td>
				<td>
					<input lay-verify="contacts_tel" readonly class="layui-input" id="contacts_tel" name="contacts_tel" style="color: gray; width: 190px">
				</td>
				<td><label class="layui-form-label">供应商地址</label></td>
				<td>
					<input lay-verify="customer_adress" readonly class="layui-input" id="customer_adress" name="customer_adress" style="color: gray; width: 190px">
				</td>
			</tr>
			<tr style="height:10px"></tr>
				<tr>
					<td> <label class="layui-form-label">备注</label>
                    </td>
					<td >
						<input class="layui-input" id="remark" name="remark" style="width: 190px" placeholder="请选输入备注信息">
					</td>
					</tr>
		</table>
		</xblock>
		<xblock>
			<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="cancellingStockForm" style="margin-left:250px; margin-bottom: 10px">提交</button>
			&emsp;&emsp;&emsp;&emsp;<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button>
		</xblock>
	</form>
</div>

<!-- 打印表单框 -->
<div id="dybdDivID" hidden="hidden">
	<div id="dyDiv" style="width: 100%;overflow-y:scroll;height: 549px">
		<table style="width: 100%;">
			<tr>
				<td align="center" rowspan="2">
					<img alt="" src="${pageContext.request.contextPath }/images/title.jpg">
				</td>
				<td align="center" colspan="2">
					<h1><span class="xt_title"></span></h1>
				</td>
			</tr>
			<tr>
				<td align="center" colspan="2">
					<h1>退库单</h1>
				</td>
			</tr>
			<tr style="height:3px"></tr>
			<tr>
				<td colspan="3" width="100%" align="center">
					<table width="70%">
						<tr>
							<td width="40%">
								退库单号：<span id="d1"></span>
							</td>
							<td width="30%">
								到货日期：<span id="d2"></span>
							</td>
							<td rowspan="7" width="30%">
								<img width="200px" id="bd_img"/>
							</td>
						</tr>
						<tr>
							<td>
								创建时间：<span id="d3"></span>
							</td>
							<td>
								窗口时间：<span id="d4"></span>
							</td>
						</tr>
						<tr>
							<td>
								客户名称：<span id="d5"></span>
							</td>
							<td>
								到货地址：<span id="d6"></span>
							</td>
						</tr>
						<tr>
							<td>
								客户地址：<span id="d7"></span>
							</td>
							<td>
								交货道口：<span id="d8"></span>
							</td>
						</tr>
						<tr>
							<td>
								发货联系人：<span id="d9"></span>
							</td>
							<td>
								收货联系人：<span id="d10"></span>
							</td>
						</tr>
						<tr>
							<td>
								联系电话：<span id="d11"></span>
							</td>
							<td>
								联系电话：<span id="d12"></span>
							</td>
						</tr>
						<tr>
							<td>
								备注：<span id="d13"></span>
							</td>
							<td>
								备注：<span id="d14"></span>
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td colspan="6"  width="100%" align="center">
					<table id="dytable" lay-filter="dytable">
					</table>
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td align="center">
					发货人签字：
				</td>
				<td>
					承运商签字：
				</td>
				<td>
					收货人签字：
				</td>
			</tr>
			<tr>
				<td align="center">
					时间：
				</td>
				<td>
					时间：
				</td>
				<td>
					时间：
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					1. 发货时务必填全发货零件信息。
				</td>
			</tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					2. 收货数量按实际数量核对签收。
				</td>
			</tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					3. 单据一式三联，发货、收货、收货回单。
				</td>
			</tr>
		</table>
	</div>
	<xblock>
		<div align="right" style="margin-bottom: 0px;">
			<button type="button" id="dayingTable" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
		</div>
	</xblock>
</div>

<div id="materielDiv" hidden="hidden">
	<table class="layui-hide" id="materielTable" lay-filter="materielTable"></table>
</div>

<div id="cancellingStockDetailDiv" hidden="hidden">
	<form class="layui-form" id="cancellingStockDetailForm">
		<div class="layui-form-item">
			<input id="detailId" name="id" hidden="hidden">
		</div>
		<div class="layui-form-item">
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 18px;">退库单号</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="cancellingNumber" class="layui-input" type="text" id="detailCancellingNumber" name="cancellingNumber" style="width:200px">
		      	</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">物料名称</label>
		      	<div class="layui-input-inline" style="width:200px">
					<select id="materialId" name="materialId" class="layui-select" lay-verify="materialId" lay-filter="materialId">
						<option value="">请选择物料</option>
					</select>
				</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<div class="layui-form-item">
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">预计数量</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="materialQuantity" class="layui-input" type="text" id="materialQuantity" name="materialQuantity" style="width:200px">
		      	</div>
			</div>
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">实际退库</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="actualQuantity" class="layui-input" type="text" id="actualQuantity" name="actualQuantity" style="width:200px">
		      	</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<br>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="cancellingStockDetailForm" style="margin-left:350px">提交</button>
		&emsp;&emsp;&emsp;&emsp;
		<button class="layui-btn layui-btn-primary">取消</button>
	</form>
</div>

<!-- 顶部搜索框 -->
<div class="x-body">
     <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select class="layui-input" name="keyword01" id="keyword01" lay-verify="keyword01"  lay-filter="keyword01">
								<option value="">请选择退库原因</option>
								<c:forEach items="${reasonList}" var="reason">
									<option value="${reason.cancellingReason}">${reason.cancellingReason}</option>
								</c:forEach>
							</select>
						</div>
					</td>


					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="selectState" name="selectState">
								<option value="">请选择</option>
								<option value="1">已退库</option>
								<option value="0">未退库</option>
							</select>
						</div>
					</td>
                         <td >
                         
						<input class="layui-input" id="startTime" placeholder="请输入开始时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px"> -
						<input class="layui-input" id="endTime" placeholder="请输入结束时间" autocomplete="off" style="display: inline; width: 180px"> 
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload1"><i class="layui-icon layui-icon-search"></i>检索</button>
	</div>
 	<%--<h2 style="text-align: center;color:#666">退库单</h2>--%>
 	<!-- 退库单头部按钮 -->
   	<xblock>
		<button id="addCancellingStock" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>新增退库单</button>
		<button id="deletes" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
		<!-- <button id="deleteCancellingStocks" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量取消</button>
		<button class="layui-btn layui-btn-danger" id="restors"><i class="layui-icon layui-icon-delete"></i>批量恢复</button> -->
		<!-- <button class="layui-btn layui-btn-danger" id="dybd"><i class="layui-icon layui-icon-upload-drag"></i>打印表单</button> -->
		<!-- <button id="messaging" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-release"></i>发送消息</button> -->
   	</xblock>
   	<!-- 退库单列表 -->
 	<table class="layui-hide" id="cancellingStockTable" lay-filter="cancellingStockTable"></table>
 	<!-- 退库单行编辑 -->
 	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
	</script>

	<div id='detailDiv' hidden>
		<%--<h2 style="text-align: center;color:#666">退库单详情</h2>--%>
		<!-- 退库单详情头部按钮 -->
	 	<xblock>
			<button id="addDetail" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>选择物料</button>
			<button id="delsDetail" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	 	</xblock>
		<!-- 退库单详情列表 -->
		<table class="layui-hide" id="cancellingStockTableDetail" lay-filter="cancellingStockTableDetail"></table>
 	</div>
	<!-- 退库单详情的编辑 -->
 	<script type="text/html" id="rowToolbarDetail">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
	</script>
	<!-- 库存物料列表 -->
	<div id='inventoryInfoDiv' hidden="hidden">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<!-- <td>
							<input class="layui-input" name="materiel_name" id="materiel_name" placeholder="请输入中文名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td> -->
						<td>
							<input class="layui-input" name="materiel_num" id="materiel_num" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			<a style="margin-top: 10px; margin-left: 10px" class="layui-btn layui-btn-normal" id="selectMateriel" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</a>
		</div>
		<table class="layui-hide" id="inventoryInfoTable" lay-filter="inventoryInfoTable"></table>
		<xblock>
			<button id="addInventoryInfo" class="layui-btn layui-btn-blue" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>
	 	</xblock>
	</div>

</div>

<script type="text/javascript">
    var cancellingNumber;
    var customerID = 0;
    var warehouseID = 0;
    var source = 1;
    var tableStatus;
	layui.use(['table','layer','upload','form','laydate'], function(){
		table = layui.table;
		var layer = layui.layer;
		var form = layui.form;
		var laydate = layui.laydate;
		laydate.render({
	    	elem: '#startTime' //开始时间
	    	,type: 'datetime'
	  	});
		laydate.render({
	    	elem: '#endTime' 	//结束时间
	    	,type: 'datetime'
	  	});
		var $ = layui.jquery, active = {
			reload1:function () {
				var keyword01 = $("#keyword01").val();
				var selectState = $("#selectState").val();
				var type = $("#type").val();
				var keyword03 = " and type = "+type+" ";
					
					var startTime = $.trim($("#startTime").val());
					if(startTime != null && startTime != ""){
						keyword03 = keyword03 + " and createDate >= '"+startTime+""+"' ";
					}
					var endTime = $.trim($("#endTime").val());
					if(endTime != null && endTime != ""){
						keyword03 = keyword03 + " and createDate <= '"+endTime+"' ";
					}
		              
				table.reload('cancellingStockTable',{
					method:'get',
					where:{"cancellingReason":keyword01,"status":selectState,"keyword03":keyword03}
					,page: {
	                    curr: 1//重新从第 1 页开始
	                }
				});
			},
			reload:function () {
				var materiel_name=$('#materiel_name').val();
	    		var materiel_num=$('#materiel_num').val();
	    		/* var verify = /^[0-9,]*$/;
	    		if(verify.test(materiel_num)){ */
	    			var split = materiel_num.split(',')
	    			if(split.length <= 5){
	    				table.reload('inventoryMatereil',{
							method:'get'
							,where:{"materielName":materiel_name,"materielNum":materiel_num}
			         		,page: {
			                    curr: 1//重新从第 1 页开始
			                }
						});
	    			}else{
	    				layer.msg("最多可同时查5个！");
	    			}
	    		/* }else{
	    			layer.msg("只能输入数字和英文逗号！");
	    		} */
			}
		}
		$('.layui-btn').on('click', function(){
			var type = $(this).data('type');
			active[type] ? active[type].call(this) : '';
		});
		
		//退库日期控件
		laydate.render({
        	elem: '#createDate',
        	type: 'datetime'
        });
		$("#createDate").val(curentTime())
		//点击行checkbox选中
	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
	        var index = $(this).attr('data-index');
	        var tableBox = $(this).parents('.layui-table-box');
	        //存在固定列
	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
	        } else {
	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
	        }
	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
	        if (checkCell.length>0) {
	            checkCell.click();
	        }
	    });

	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
	        e.stopPropagation();
	    });

	  	//监听复选框事件，被选中的行高亮显示
	    table.on('checkbox(cancellingStockTable)', function(obj){
	    	if(obj.checked == true && obj.type == 'all'){
		        //点击全选
		        $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
		    }else if(obj.checked == false && obj.type == 'all'){
		        //点击全不选
		        $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
		    }else if(obj.checked == true && obj.type == 'one'){
		        //点击单行
			    if(obj.checked == true){
			          obj.tr.addClass('layui-table-click');
			    }else{
			          obj.tr.removeClass('layui-table-click');
			    }
		    }else if(obj.checked == false && obj.type == 'one'){
		        //点击全选之后点击单行
		        if(obj.tr.hasClass('layui-table-click')){
		        	obj.tr.removeClass('layui-table-click');
		        }
		    }
	    });

	  	//表单的下拉框监听事件
	    form.on('select(source)', function(data){
	        var id = data.value;	//改变后的值
	        selectWare(id);
	        form.render();
	    });

	    form.on('select(warehouseId)', function(data){
	    	var id = data.value;	//改变后的值
	    	//根据仓库ID获取管理员信息
	    	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getWarehouseById.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                   	//赋值
                   	$("#warehouse_address").val(datas[0].warehouse_address);
                   	$("#userName").val(datas[0].userName);
                   	$("#phone").val(datas[0].phone);
                }
          	});
	    	//根据仓库ID获取物料信息
	    	/* $.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getMaterielByWarehouseId.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                	//设置下拉列表中的值的属性
                    for ( var i = 0; i < datas.length; i++) {
                    	//增加下拉列表。
                      	$("#materielId").append("<option value='"+datas[i].id+"'>"+datas[i].materiel_name+"</option>");
        			}
                }
          	}); */
	    });

	  	//根据客户ID获取联系人信息
	    form.on('select(clientId)', function(data){
	    	var id = data.value;	//改变后的值
	    	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getClientById.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                   	//赋值
                   	$("#contacts_name").val(datas[0].contacts_name);
                   	$("#contacts_tel").val(datas[0].contacts_tel);
                   	$("#customer_adress").val(datas[0].customer_adress);
                }
          	});
	    });

	  	//根据物料ID获取库存数量
	   /*  form.on('select(materielId)', function(data){
	    	var id = data.value;	//改变后的值
	    	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockDetailManager/getQuantityByMid.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                   	//赋值
                   	$("#materialQuantity").val(datas[0].mNum);
                }
          	});
	    }); */
	    var type = $("#type").val();
		var keyword03 = " and type = "+type+" ";
		/* 退库单列表 */
		table.render({
			elem: '#cancellingStockTable'
			,where:{"keyword03":keyword03}
			,url:'${pageContext.request.contextPath }/cancellingStockManager/listPageCancellingStock.do'
			,title: '退库单列表'
			,id :'cancellingStockTable'
			,limits:[10,20,30]
			,toolbar: '#toolbarDemo'
			,cols: [[
				{type: 'checkbox', fixed: 'left', },
			  	{field:'', title:'序号', type:'numbers', align:'center'},
			  	{field:'cancellingNumber', title:'退库单号', align:'center'},
			  	{field:'createDate', title:'创建时间', align:'center'
			  		,
                  	templet: function(d){
                  		return changeDateFormat(d.createDate)
                  }},
			  	{field:'warehouse_name', title:'仓库名称', align:'center'},
			  	{field:'warehouse_address', title:'仓库地址', align:'center'},
			  	{field:'userName', title:'仓库管理员', align:'center'},
			  	{field:'phone', title:'管理员电话', align:'center'},
			  	{field:'customer_name', title:'供应商名称', align:'center'},
			  	{field:'customer_adress', title:'供应商地址', align:'center'},
			  	{field:'contacts_name', title:'供应商负责人', align:'center'},
			 	{field:'contacts_tel', title:'负责人电话', align:'center'},
			  	{field:'cancellingReason', title:'退库原因', align:'center'},
			  	{field:'cancellingStatus', title:'状态', align:'center'},
                {field:'customer_order', title:'供应商单号', align:'center'},
                /* {field: 'flag',title: '是否取消',align:'center' ,
                	templet: function(d){
                    var value = d.flag;
                    if(value == 0){
                        value = "已取消"
                    }else if(value == 1){
                        value = "已恢复"
                    }else if(value == 2){
                        value = "未操作"
                    }
                    return value;
                }},
                {field: 'cancellation',title: '取消人',align:'center'},
                {field: 'cancellation_time',title: '取消时间',align:'center'
                	,
                  	templet: function(d){
                  		if(d.cancellation_time != "" && d.cancellation_time != null) {
                  			return changeDateFormat(d.cancellation_time);
                  		}else {
                  			return "";
                  		}
                  		
                  }},
                {field: 'restorer',title: '恢复人',align:'center'},
                {field: 'restorer_time',title: '恢复时间',align:'center'
                	,
                  	templet: function(d){
                  		if(d.restorer_time != "" && d.restorer_time != null) {
                  			return changeDateFormat(d.restorer_time);
                  		}else {
                  			return "";
                  		}
                  		
                  }}, */
                {field: 'remark',title: '备注',align:'center'},
			  	{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar',width:100, align: 'center'}
			  	]]
			,page: true
			,done : function(){
				$("#cancellingStockTableDetail").addClass("layui-hide");
				$("#detailDiv").attr("hidden","hidden");
				$("#barCodeDiv").attr("hidden","hidden");
				$('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
		});
	    /* 打印单据 */
        table.render({
            elem: '#dytable'
            //,url:'${pageContext.request.contextPath }/receiveDetail/list.do'
            ,title: '明细表'
            ,cols: [[
                 {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                 {field:'materiel_num', title:'QAD/SAP', align:'center', width: 250,
	                    templet: function (row){
	                    	var value = "";
	                    	if(null != row.materiel){
	                    		value = row.materiel.materiel_num;
                            }
                            return value;
                        },
                 },
                 /* {field:'brevity_num', title:'供应商零件号', align:'center', width: 200,
	                    templet: function (row){
	                    	var value = "";
	                    	if(null != row.materiel){
	                    		value = row.materiel.brevity_num;
                            }
                            return value;
                        },
                 }, */
                 {field:'materiel_name', title:'中文描述', align:'center', width: 350,
	                    templet: function (row){
	                    	var value = "";
	                    	if(null != row.materiel){
	                    		value = row.materiel.materiel_name;
                            }
                            return value;
                        },
                 },
                 {field:'unit', title:'单位', align:'center', width: 87,
	                    templet: function (row){
	                    	var value = "";
	                    	if(null != row.materiel){
	                    		value = row.materiel.unit;
                            }
                            return value;
                        },
                 },
                 {field:'packing_quantity', title:'单包装数', width: 100, align:'center',
	                    templet: function (row){
	                    	var value = "";
	                    	if(null != row.materiel){
	                    		value = row.materiel.packing_quantity;
                            }
                            return value;
                        },
                 },
                 {field:'sendNum', title:'发货包装数', align:'center', width: 100,
	                    templet: function (row){
	                    	var value = "";
	                    	if(null != row.materiel && materialQuantity != 0){
	                    		value = Math.ceil(row.materialQuantity/row.materiel.packing_quantity);
                            }
                            return value;
                        },
                 },
                 {field:'materialQuantity', title:'发货件数', align:'center', width: 100},
                 {field:'receiveNum', title:'实收包装数', align:'center', width: 100,
	                    templet: function (row){
	                    	var value = 0;
	                    	if(null != row.materiel && row.actualQuantity != 0){
	                    		value = Math.ceil(row.actualQuantity/row.materiel.packing_quantity);
                            }
                            return value;
                        },
                 },
                 {field:'actualQuantity', title:'实收件数', align:'center', width: 100},
                 {field:'pici', title:'批号/备注', align:'center', width: 150},
                 {field:'mbatch', title:'批次', align:'center'},
				 {field:'location', title:'库位', align:'center'},
   				 {field:'isUnpacking', title:'是否拆箱', align:'center',
                 	templet: function (row){
                    	var value = "";
                    	if(row.isUnpacking == 0){
                    		value = "否";
                    	}else if(row.isUnpacking == 1){
                    		value = "是";
                         }
                         return value;
                     }
			 	 },
             ]]
            ,page: false
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
		//退库单推送
		$('#messaging').click(function(obj){
			var rowData = table.checkStatus('cancellingStockTable');
			var data = rowData.data;
        	var str = "";
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        	}else if(data.length > 1){
        		toastr.warning("只能选择一条记录！");
        	}else{
        		var roder = data[0].cancellingNumber;
        		$.ajax({
			    	type:'post',
			    	url:'${pageContext.request.contextPath }/cancellingStockManager/sendCancellingStock.do',
			    	data:{"roder":roder},
			    	dataType : "json",
			    	success:function(data){
			    		if(data>0){
			    			toastr.success("发送成功！");
			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
								//关闭模态框
								// 父页面刷新
								window.location.reload();
							},1000);
			    		}else{
			    			toastr.error("发送失败！");
			    		}
			    	}
			    })
        	}
		});

		//新增退货单
		$('#addCancellingStock').click(function(){
			layer.open({
				type: 1 				//Page层类型
				,area: ['680px', ''] 	//宽  高
				,title: '新增'
				,shade: 0.6 			//遮罩透明度
				,shadeClose: true 		//点击遮罩关闭
				,maxmin: true 			//允许全屏最小化
				,anim: 1 				//0-6的动画形式，-1不开启
				,content: $('#cancellingStockDiv')
				,success: function () {
					document.getElementById("cancellingStockForm").reset();
					$("#id").val("")
                 	$("#cancellingNumber").val(curentTimeNumber());	//调用方法，自动生成退货单号
                  	$("#createDate").val(curentTime());	//调用方法，获取当前时间
				}
				,end: function () {
					var formDiv = document.getElementById('cancellingStockForm');
					formDiv.style.display = '';
					layer.close();
				}
			});
		});

		//批量删除退货单
		$('#deleteCancellingStocks').click(function(obj){
        	var rowData = table.checkStatus('cancellingStockTable');
			var data = rowData.data;
        	var str = "";
        	var b;
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        		return;
        	}

        	for (var i = 0; i < data.length; i++){
        		//console.log("***dfgsdg*******"+data[i].status)
				if(data[i].status == "1"){
					console.log("**********"+data[i].status)
					//toastrStyle();
					//toastr.warning("审批通过，不能删除！");
					b=0;
				}if(data[i].flag == 0){
                    toastr.warning("对不起，已取消的数据不能取消！");
                    return;
                }
        	}
			if(b!=0){

        		for(var i=0;i<data.length;i++){
            		str += data[i].id;
            		if(i != data.length-1){
            			str += ",";
            		}
            	}
        		layer.confirm('确定取消吗？', function(index){
    				$.ajax({
    			    	type:'post',
    			    	url:'${pageContext.request.contextPath }/cancellingStockManager/deleteCancellingStock.do',
    			    	data:{"ids":str},
    			    	dataType : "json",
    			    	success:function(data){
    			    		if(data>0){
    			    			toastr.success("取消成功！");
    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
    								//关闭模态框
    								// 父页面刷新
    								window.location.reload();
    							},1000);
    			    		}else{
    			    			toastr.error("取消失败！");
    			    		}
    			    	}
    			    })
    		    layer.close(index);
    			});
			}else{
        		toastrStyle();
				toastr.warning("已退库，不能取消！");

        	}
		});
		//批量删除
		$('#deletes').click(function(obj){
        	var rowData = table.checkStatus('cancellingStockTable');
			var data = rowData.data;
        	var str = "";
        	var b;
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        		return;
        	}

        	for (var i = 0; i < data.length; i++){
        		//console.log("***dfgsdg*******"+data[i].status)
				if(data[i].status == "1"){
					console.log("**********"+data[i].status)
					//toastrStyle();
					//toastr.warning("审批通过，不能删除！");
					b=0;
                }
        	}
			if(b!=0){

        		for(var i=0;i<data.length;i++){
            		str += data[i].id;
            		if(i != data.length-1){
            			str += ",";
            		}
            	}
        		layer.confirm('确定删除吗？', function(index){
    				$.ajax({
    			    	type:'post',
    			    	url:'${pageContext.request.contextPath }/CancellingStocksDetailPiLiang/delete.do',
    			    	data:{"ids":str},
    			    	dataType : "json",
    			    	success:function(data){
    			    		if(data>0){
    			    			toastr.success("删除成功！");
    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
    								//关闭模态框
    								// 父页面刷新
    								window.location.reload();
    							},1000);
    			    		}else{
    			    			toastr.error("删除失败！");
    			    		}
    			    	}
    			    })
    		    layer.close(index);
    			});
			}else{
        		toastrStyle();
				toastr.warning("已退库，不能删除！");

        	}
		});
		$('#restors').click(function(obj){
        	var rowData = table.checkStatus('cancellingStockTable');
			var data = rowData.data;
        	var str = "";
        	var b;
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        		return;
        	}

        	for (var i = 0; i < data.length; i++){
        		//console.log("***dfgsdg*******"+data[i].status)
				if(data[i].status == "1"){
					console.log("**********"+data[i].status)
					//toastrStyle();
					//toastr.warning("审批通过，不能删除！");
					b=0;
				}if(data[i].flag == 1){
                    toastr.warning("对不起，已恢复的数据不能恢复！");
                    return;
                }
        	}
			if(b!=0){

        		for(var i=0;i<data.length;i++){
            		str += data[i].id;
            		if(i != data.length-1){
            			str += ",";
            		}
            	}
        		layer.confirm('确定恢复吗？', function(index){
    				$.ajax({
    			    	type:'post',
    			    	url:'${pageContext.request.contextPath }/cancellingStockManager/restor.do',
    			    	data:{"ids":str},
    			    	dataType : "json",
    			    	success:function(data){
    			    		if(data>0){
    			    			toastr.success("恢复成功！");
    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
    								//关闭模态框
    								// 父页面刷新
    								window.location.reload();
    							},1000);
    			    		}else{
    			    			toastr.error("恢复失败！");
    			    		}
    			    	}
    			    })
    		    layer.close(index);
    			});
			}else{
        		toastrStyle();
				toastr.warning("已退库，不能恢复！");

        	}
		});
		//打印表单
        $("#dybd").click(function(){
        	var checkStatus = table.checkStatus('cancellingStockTable')
            var datas = checkStatus.data;
            if(datas.length!=1){
                toastr.warning("请选择一条记录！");
            }else{
            	var data = datas[0]
	            layer.open({
	                type: 1 					//Page层类型
	                ,area: ['1450px', '650px'] 			//宽  高
	                ,title: '打印表单'
	                ,shade: 0.6 				//遮罩透明度
	                ,maxmin: true 				//允许全屏最小化
	                ,anim: 1 					//0-6的动画形式，-1不开启
	                ,content: $('#dybdDivID')
	                ,end: function () {
	                    var formDiv = document.getElementById('dybdDivID');
	                    formDiv.style.display = '';
	                }
	                ,success: function(){
                        $("#d1").html(data.cancellingNumber);
                        $("#d3").html(data.createDate);
                        $("#d5").html(data.customer_name);
                        $("#d7").html(data.customer_adress);
                        $("#d9").html(data.userName);
                        $("#d10").html(data.contacts_name);
                        $("#d11").html(data.phone);
                        $("#d12").html(data.contacts_tel);
                      //二维码路径
                        var path = '${pageContext.request.contextPath}/'
                        $.ajax({
                            type:'post',
                            data:'code='+data.cancellingNumber,
                            url:'${pageContext.request.contextPath}/label/erWeiMa.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                            	path = path+data.path;
                            }
                        });
                        $("#bd_img").attr("src",path)
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'cancellingNumber='+data.cancellingNumber,
                            url:'${pageContext.request.contextPath}/CancellingStocksDetailPiLiang/queryAllByMution.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (json) {
                                console.log(json);
                            	newData = json.data;
                            }
                        });
                        table.reload('dytable',{
                            data : newData
                            ,limit:newData.length
                        });
	                }
	            });
            }
        });
        $("#dayingTable").click(function(){
			//var innerHTML = document.getElementById("dyDiv").innerHTML;
        	//printpage(innerHTML)
		    var obj =document.getElementById('dyDiv')
			var newWindow=window.open("打印窗口","_blank");//打印窗口要换成页面的url
			var css='<style>'
                //+"#dyTable td{border:1px solid #00000080;}"
                +'[lay-id="dytable"] table{border:1px solid #F00;border-collapse:collapse;}'
                +'[lay-id="dytable"] table td{border:1px solid #222;}'
                +'[lay-id="dytable"] table th{border:1px solid #222;font-size: 20px;}'
                +'[lay-id="dytable"] table th span{color: black;}'
                +'</style>'; 
			var docStr =  css+ obj.innerHTML;
		    newWindow.document.write(docStr);
		    newWindow.document.close();
		    setTimeout(function () {
			    newWindow.print();
			    newWindow.close();
		    }, 100);
		});
		//退库单的编辑
		table.on('tool(cancellingStockTable)', function(obj){
			var data = obj.data;
			var checkStatus = table.checkStatus(obj.data.id);
			$('#cancellingStockId').val(obj.data.id);
			if(obj.event === 'edit'){
				if(data.cancellingStatus == "已退库"){
					toastr.warning("已退库，不能编辑");
				}else{
					layer.open({
						type: 1 				//Page层类型
						,area: ['680px', ''] 	//宽  高
						,title: '编辑'
						,shade: 0.6 			//遮罩透明度
						,maxmin: true 			//允许全屏最小化
						,anim: 1 				//0-6的动画形式，-1不开启
						,content: $('#cancellingStockDiv')
						,success: function () {
							//回显表单数据
							for(var i=0;i<Object.entries(data).length;i++) {
								var id = '#' + Object.entries(data)[i][0];
								var text = Object.entries(data)[i][1];
								$(id).val(text);
							}
							var id = data.source;	//改变后的值
					        selectWare(id);
					        $("#warehouseId").val(data.warehouseId)
							form.render();
						}
						,end: function () {
							var formDiv = document.getElementById('cancellingStockForm');
						  	formDiv.style.display = '';
						  	layer.closeAll();
					  	}
					});
				}
			}
		});

		/**
		 * 退库单的提交(新增/编辑)
		 */
		form.on('submit(cancellingStockForm)', function (data) {
			var title = "新增";
			var url = '${pageContext.request.contextPath}/cancellingStockManager/saveCancellingStock.do';
			var id = $.trim($("#cancellingStockId").val());
			if(id != "" && id != null && id != 'undefined'){
				url = '${pageContext.request.contextPath}/cancellingStockManager/updateCancellingStock.do';
				title = "修改";
			}
			$.ajax({
				url : url,
				data: $("#cancellingStockForm").serialize(),
				cache : false,
				type : "post",
			}).done(
				function(res) {
					if (res > 0) {
						toastr.success(title + '成功！');
					}else{
						toastr.error(title + '失败！');
					}
					setTimeout(function(){
						location.reload();
					},1000);
				}
			).fail(
				function(res) {
					toastr.error(title + '失败！');
					setTimeout(function(){
						location.reload();
					},1000);
				}
			)
			return false;
		});

		//监听行单击事件(退库单详情列表)
		table.on('row(cancellingStockTable)', function(obj){
			$("#cancellingStockTableDetail").removeClass("layui-hide");
			$('#detailDiv').removeAttr("hidden");
			$('#cancellingStockNumber').val(obj.data.cancellingNumber);
			$('#cancellingType').val(obj.data.source);
			$('#warehouseStockId').val(obj.data.warehouseId);
			$('#customerId').val(obj.data.clientId);
			customerID = obj.data.clientId;
			warehouseID = obj.data.warehouseId;
			cancellingNumber = obj.data.cancellingNumber;
			source = obj.data.source;
			tableStatus = obj.data.status;
			flag= obj.data.flag;
			//点击退库单行单击事件时根据退库单状态展示不同的退库单详细
            //1表示已退库
            if (obj.data.status == 1) {
            	table.render({
    				elem: '#cancellingStockTableDetail'
    				,url:'${pageContext.request.contextPath}/CancellingStocksDetailPiLiang/list.do?cancellingNumber='+cancellingNumber
    				,title: '退库单详情列表'
    				,limits:[10,20,30]
    				,toolbar: '#toolbarDemo'
   					,request: {   //如果无需自定义请求参数，可不加该参数
   		                pageName: 'page' //页码的参数名称，默认：page
   		                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
   		            }
   		            ,response: {   //如果无需自定义数据响应名称，可不加该参数
   		                countName: 'total' //规定数据总数的字段名称，默认：count
   		                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
   		            }
    				,cols: [[
    				  	{type: 'checkbox', fixed: 'left', },
    				  	{field:'cancellingNumber', title:'退库单号', hide:true},
    				  	{field:'materiel_name', title:'中文名称', align:'center', event: 'collapse',
							templet: function(d) {
    							return '<div style="position: relative;'+'padding: 0 10px 0 20px;">' + d.materiel_name + '<i style="left: 0px;" lay-tips="展开" class="layui-icon layui-colla-icon layui-icon-right"></i></div>'
    						}
    				  	},
    				  	{field:'materiel_num', title:'SAP/QAD', align:'center'},
    				  	/* {field:'brevity_num', title:'零件号', align:'center'}, */
    				  	//{field:'materiel_size', title:'物料规格', align:'center'},
    				  	//{field:'materiel_properties', title:'物料型号', align:'center'},
    				  	{field:'mNum', title:'库存总数', align:'center'},
    					//{field:'goodQuantity', title:'良品数量', align:'center'},
    				  	{field:'materialQuantity', title:'预计数量', align:'center'},
    				  	{field:'actualQuantity', title:'实际退库', align:'center'},
    				  	/*{field:'storageLocation', title:'推荐库位', align:'center'},
                        {field:'single_num', title:'单个数量', align:'center'},
                        {field:'big_num', title:'大箱数量', align:'center'},
                        {field:'small_num', title:'小箱数量', align:'center'}, */
    				  	{field:'mbatch', title:'批次', align:'center'},
	   					{field:'location', title:'库位', align:'center'},
    	   				{field:'isUnpacking', title:'是否拆箱', align:'center',
 	                    	templet: function (row){
 		                    	var value = "";
 		                    	if(row.isUnpacking == 0){
 		                    		value = "否";
 		                    	}else if(row.isUnpacking == 1){
 		                    		value = "是";
 	                            }
                                 return value;
 	                        }
 					 	},
    				  	]]
    				,page: true
    				,done : function(){
    	                $('th').css({
    	                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
    	                    //'font-size': 10,
    	                })
    	            }
    			});
            } else {
            	table.render({
    				elem: '#cancellingStockTableDetail'
    				,url:'${pageContext.request.contextPath}/CancellingStocksDetailPiLiang/list.do?cancellingNumber='+cancellingNumber
    				,title: '退库单详情列表'
    				,limits:[10,20,30]
    				,toolbar: '#toolbarDemo'
   					,request: {   //如果无需自定义请求参数，可不加该参数
   		                pageName: 'page' //页码的参数名称，默认：page
   		                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
   		            }
   		            ,response: {   //如果无需自定义数据响应名称，可不加该参数
   		                countName: 'total' //规定数据总数的字段名称，默认：count
   		                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
   		            }
    				,cols: [[
    				  	{type: 'checkbox', fixed: 'left', },
    				  	{field:'cancellingNumber', title:'退库单号', hide:true},
    				  	{field:'materiel_name', title:'中文名称', align:'center'/* , event: 'collapse',
							templet: function(d) {
    							return '<div style="position: relative;'+'padding: 0 10px 0 20px;">' + d.materiel_name + '<i style="left: 0px;" lay-tips="展开" class="layui-icon layui-colla-icon layui-icon-right"></i></div>'
    						} */
    				  	},
    				  	{field:'materiel_num', title:'SAP/QAD', align:'center'},
    				  	/* {field:'brevity_num', title:'零件号', align:'center'}, */
    				  	//{field:'materiel_size', title:'物料规格', align:'center'},
    				  	//{field:'materiel_properties', title:'物料型号', align:'center'},
    				  	{field:'mNum', title:'库存总数', align:'center'},
    					//{field:'goodQuantity', title:'良品数量', align:'center'},
    				  	{field:'materialQuantity', title:'预计数量', align:'center', edit: true, templet: function (row){
    						return '<span style="color: blue">'+row.materialQuantity+'</span>';
    					}},
    				  	{field:'actualQuantity', title:'实际退库', align:'center'},
    				  	//{field:'storageLocation', title:'推荐库位', align:'center'},
    				  	/* {field:'single_num', title:'单个数量', align:'center'},
                        {field:'big_num', title:'大箱数量', align:'center'},
                        {field:'small_num', title:'小箱数量', align:'center'}, */
    				  	{field:'mbatch', title:'批次', align:'center'},
	   					{field:'location', title:'库位', align:'center'},
    	   				{field:'isUnpacking', title:'是否拆箱', align:'center',
 	                    	templet: function (row){
 		                    	var value = "";
 		                    	if(row.isUnpacking == 0){
 		                    		value = "否";
 		                    	}else if(row.isUnpacking == 1){
 		                    		value = "是";
 	                            }
                                 return value;
 	                        }
 					 	},
    				  	]]
    				,page: true
    				,done : function(){
    	                $('th').css({
    	                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
    	                    //'font-size': 10,
    	                })
    	            }
    			});
            }

		});
		
		 
		//展示物料（物料列表）
		$('#addDetail').click(function(){
			if(flag == 0){
				toastr.warning("对不起，已取消的数据不能操作！");
				return;
			}
			if(tableStatus == 0){
				layer.open({
					type: 1 		//Page层类型
					,area: ['1000px', '650px'] //宽  高
					,title: '物料列表'
					,shade: 0.1 	//遮罩透明度
					,shadeClose: true //点击遮罩关闭
					,anim: 1 		//0-6的动画形式，-1不开启
					,content: $('#inventoryInfoDiv')
					,success: function () {
						layui.use(['table'], function(){
							var table = layui.table;
							table.render({
								elem: '#inventoryInfoTable'
								,url:'${pageContext.request.contextPath}/jingJianUnpacking/selectAllGoodOnly.do?customerId='+customerID//+'&source='+source
								,title: '物料列表'
								,id :'inventoryMatereil'
								,cols: [[
									{type: 'checkbox', fixed: 'left', },
									{field:'materiel_num', title:'SAP/QAD', align:'center'},
									{field:'materiel_name', title:'中文名称', align:'center'},
									/* {field:'brevity_num', title:'零件号', align:'center'}, */
									{field:'mNum', title:'库存', align:'center'},
									{field:'mBatch', title:'批号', align:'center'},
									{field:'location', title:'库位', align:'center'},
									{field:'isUnpacking', title:'是否拆箱', align:'center',
				                    	templet: function (row){
					                    	var value = "";
					                    	if(row.isUnpacking == 0){
					                    		value = "否";
					                    	}else if(row.isUnpacking == 1){
					                    		value = "是";
				                            }
			                                return value;
				                        }
									},
			     				]]
			                    ,page: true
			                    ,done : function(){
			                        $('th').css({
			                            'background-color': '#009688', 'color': '#fff','font-weight':'bold',
			                        })
			                    }
							});
				        });
						form.render();
					}
					,end: function () {
						var formDiv = document.getElementById('inventoryInfoDiv');
						formDiv.style.display = '';
						layer.closeAll();
					}
				});
			}else{
				toastr.warning("对不起，已退库的数据不能操作！");
			}
		});

		//把物料加入退库单详情
		$('#addInventoryInfo').click(function(obj){
			//alert("e")
			var cancellingNumber = $('#cancellingStockNumber').val();
			var source = $('#cancellingType').val();
			var warehouseId = $('#warehouseStockId').val();
			var customerId = $('#customerId').val();
			//var rowData = table.checkStatus('inventoryInfoTable');
			var rowData = table.checkStatus('inventoryMatereil');
			var data = rowData.data;
			var str = "";
			var mbatchs = "";
			var locations = "";
			var isUnpackings = "";
			if(data.length == 0){
				toastr.warning("请至少选择一条记录！");
			}else{
				for(var i=0;i<data.length;i++){
            		str += data[i].mid;
            		mbatchs += data[i].mBatch;
            		locations += data[i].location;
            		isUnpackings += data[i].isUnpacking;
            		if(i != data.length-1){
            			str += ",";
            			mbatchs += ",";
            			locations += ",";
            			isUnpackings += ",";
            		}
            	}
				$.ajax({
			    	type:'post',
			    	url:'${pageContext.request.contextPath }/CancellingStocksDetailPiLiang/insertPiliang.do',
			    	data:{"ids":str, "cancellingNumber":cancellingNumber, "source":source, "warehouseId":warehouseId, "customerId":customerId,"mbatchs":mbatchs,"locations":locations,"isUnpackings":isUnpackings},
			    	dataType : "json",
			    	success:function(data){
			    		if(data > 0){
			    			toastr.success("新增成功！");
			    			setTimeout(function(){
			    				//使用  setTimeout（）方法设定定时2000毫秒
								//关闭模态框
								//父页面刷新
								window.location.reload();
							},1000);
			    		}
			    	}
			    })
			    layer.closeAll();
			}
		});

		//"退库单详情"的行内编辑事件
        table.on('edit(cancellingStockTableDetail)', function(obj){
            var fieldValue = obj.value, 	//得到修改后的值
                rowData = obj.data, 		//得到所在行所有键值
                fieldName = obj.field; 		//得到字段
            	//console.log(rowData.mNum);
                max = rowData.mNum;
                if(max==''){
                	max=0;
                }
           	var firstValue = $(this).prev().text(); 	//得到修改前的值
           	//alert("修改前：" + firstValue+ "，修改后：" + fieldValue);
            var patrn = /^[0-9]*$/;
            if(!patrn.test(fieldValue)){
            	toastr.warning("只能是数字！");
            	
            	//$(this)[0].value = $(this).prev().text(); //还原值
            	setTimeout(function(){
                    window.location.reload();
                },1000);
            } else {
            	if(parseInt(fieldValue) > parseInt(max)){
            		toastr.warning("不能大于当前的库存！");
            		setTimeout(function(){
                        window.location.reload();
                    },1000);
            		
            	}else{
            		layui.use('jquery',function(){
                        var $=layui.$;
                        $.ajax({
                            type: "post",
                            url: "${pageContext.request.contextPath }/cancellingStockDetailManager/updateCancellingStockDetail4.do",
                            data: { id:rowData.id, fieldName:fieldName, fieldValue:fieldValue },
                            success: function(data){
                                if(data > 0){
                                	toastr.success("修改成功！");
                                }else{
                                	toastr.error("修改失败！");
                                	setTimeout(function(){
                                        window.location.reload();
                                    },1000);
                                }
                            }
                        });
                    });
            	} 
            	/* layui.use('jquery',function(){
                    var $=layui.$;
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath }/cancellingStockDetailManager/updateCancellingStockDetail4.do",
                        data: { id:rowData.id, fieldName:fieldName, fieldValue:fieldValue },
                        success: function(data){
                            if(data > 0){
                            	toastr.success("修改成功！");
                            }else{
                            	toastr.error("修改失败！");
                            }
                        }
                    });
                }); */
            }
            /* setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
				//关闭模态框
				// 父页面刷新
				window.location.reload();
			},1000); */
        });

      	//批量删除退货单详情
		$('#delsDetail').click(function(obj){
        	var rowData = table.checkStatus('cancellingStockTableDetail');
			var data = rowData.data;
        	var str = "";
        	var b;
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        	}else
			if(data[0].status == "0"){
				console.log("**********"+data[0].status)
				b=0;
			}
			if(b==0){
				for(var i=0;i<data.length;i++){
            		str += data[i].id;
            		if(i != data.length-1){
            			str += ",";
            		}
            	}
        		layer.confirm('确定删除吗？', function(index){
    				$.ajax({
    			    	type:'post',
    			    	url:'${pageContext.request.contextPath }/cancellingStockDetailManager/deleteCancellingStockDetail.do',
    			    	data:{"ids":str},
    			    	dataType : "json",
    			    	success:function(data){
    			    		if(data>0){
    			    			toastr.success("删除成功！");
    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
    								//关闭模态框
    								// 父页面刷新
    								window.location.reload();  
    							},1000);
    			    		}else{
    			    			toastr.error("删除失败！");
    			    		}
    			    	}
    			    })
    		    layer.close(index);
    			});
			}else{
				toastrStyle();
				toastr.warning("已退库，不能删除！");
				
			}
        	
		});
		
		/**
	     * 退库表单校验
	     */
	    form.verify({
			cancellingNumber: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '退库单号不能为空';
	    		}
	    	},
	    	createDate: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '创建时间不能为空';
	    		}
	    	},
	    	cancellingReason: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '退库原因不能为空';
	    		}
	    	},
	    	warehouseId: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '仓库名称不能为空';
	    		}
	    	},
	    	clientId: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '供应商名称不能为空';
	    		}
	    	},
	    });
	})	
</script>	

<script type="text/javascript">
function changeDateFormat(timestamp) {
	if (timestamp == null) {
		return '';
	} else {
		var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
		Y = date.getFullYear() + '-';
		M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
		D = (date.getDate()+1 < 10 ? '0'+(date.getDate()) : date.getDate())+ '      ';
		H = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours())+ ':';
        MI= (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())+':';
        S = (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
			
			
			return Y+M+D+H+MI+S;
	
	}
}
	//表格行折叠方法
	function collapseTable(options) {
	    var trObj = options.elem;
	    if (!trObj) {
	        return;
	    }
	    var accordion = options.accordion,
	        success = options.success,
	        content = options.content || '';
	    var tableView = trObj.parents('.layui-table-view'); //当前表格视图
	    var id = tableView.attr('lay-id'); //当前表格标识
	    var index = trObj.data('index'); //当前行索引
	    var leftTr = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + index + '"]'); //左侧当前固定行
	    var rightTr = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + index + '"]'); //右侧当前固定行
	    var colspan = trObj.find('td').length; //获取合并长度
	    var trObjChildren = trObj.next(); //展开行Dom
	    var indexChildren = id + '-' + index + '-children'; //展开行索引
	    var leftTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + indexChildren + '"]'); //左侧展开固定行
	    var rightTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + indexChildren + '"]'); //右侧展开固定行
	    var lw = leftTr.width() + 15; //左宽
	    var rw = rightTr.width() + 15; //右宽
	    //不存在就创建展开行
	    if (trObjChildren.data('index') != indexChildren) {
	        //装载HTML元素
	        var tr = '<tr data-index="' + indexChildren + '"><td colspan="' + colspan + '"><div style="height: auto;padding-left:' + lw + 'px;padding-right:' + rw + 'px" class="layui-table-cell">' + content + '</div></td></tr>';
	        trObjChildren = trObj.after(tr).next().hide(); //隐藏展开行
	        var fixTr = '<tr data-index="' + indexChildren + '"></tr>';//固定行
	        leftTrChildren = leftTr.after(fixTr).next().hide(); //左固定
	        rightTrChildren = rightTr.after(fixTr).next().hide(); //右固定
	    }
	    //展开|折叠箭头图标
	    trObj.find('td[lay-event="collapse"] i.layui-colla-icon').toggleClass("layui-icon-right layui-icon-down");
	    //显示|隐藏展开行
	    trObjChildren.toggle();
	    //开启手风琴折叠和折叠箭头
	    if (accordion) {
	        trObj.siblings().find('td[lay-event="collapse"] i.layui-colla-icon').removeClass("layui-icon-down").addClass("layui-icon-right");
	        trObjChildren.siblings('[data-index$="-children"]').hide(); //展开
	        rightTrChildren.siblings('[data-index$="-children"]').hide(); //左固定
	        leftTrChildren.siblings('[data-index$="-children"]').hide(); //右固定
	    }
	    success(trObjChildren, indexChildren); //回调函数
	    heightChildren = trObjChildren.height(); //展开高度固定
	    rightTrChildren.height(heightChildren + 115).toggle(); //左固定
	    leftTrChildren.height(heightChildren + 115).toggle(); //右固定
	}
	
	//生成退货单号
	function curentTimeNumber() {
		var now=new Date();
		var year = now.getFullYear();       //年
	    var month = now.getMonth() + 1;     //月
	    var day = now.getDate();            //日
	 	var hours = now.getHours(); //获取当前小时数(0-23)
   	var minutes = now.getMinutes(); //获取当前分钟数(0-59)
   	var seconds = now.getSeconds(); //获取当前秒数(0-59)
	    //var mill=now.getMilliseconds();
	    var time=year+""+add0(month)+""+add0(day)+""+add0(hours)+""+add0(minutes)+""+add0(seconds);
		return time;
	}
	function curentTime() {
		 var now=new Date();
	        var year=now.getFullYear(); 
		     var month=now.getMonth()+1; 
		     var date=now.getDate(); 
		     var hour=now.getHours(); 
		     var minute=now.getMinutes(); 
		     var second=now.getSeconds(); 
		     if (month >= 1 && month <= 9) {
		        month = "0" + month;
		    }
		    if (date >= 0 && date <= 9) {
		       date = "0" + date;
		    } 
		   if (hour >= 1 && hour <= 9) {
			  hour = "0" + hour;
		    }
		  if (minute >= 1 && minute <= 9) {
			 minute = "0" + minute;
		    }
		 if (second >= 1 && second <= 9) {
			second = "0" + second;
		    }
		var time =year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 

	       return time;
	}
	//获取当前时间

	function add0(m){return m<10?'0'+m:m }
	toastrStyle()
	function selectWare(id){
		$("#warehouseId").find("option").not(":first").remove();
    	if(id == 1){
        	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getAllWarehouse.do",
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                	console.log(datas)
                	//设置下拉列表中的值的属性
                    for ( var i = 0; i < datas.length; i++) {
                    	//增加下拉列表。
                      	$("#warehouseId").append("<option value='"+datas[i].id+"'>"+datas[i].warehouse_name+"</option>");
                    }
                }
          	});
        }else{
        	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getAllBadnessWarehouse.do",
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                	//设置下拉列表中的值的属性
                    for ( var i = 0; i < datas.length; i++) {
                    	//增加下拉列表。
                      	$("#warehouseId").append("<option value='"+datas[i].id+"'>"+datas[i].warehouse_name+"</option>");
        			}
                }
          	});
        }
    }
</script>

</body>
</html>
